/*
 * @Copyright: 2017 www.yyfax.com Inc. All rights reserved.
 */
package com.yyfax.pay.quartz.service.impl;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import com.yyfax.commons.lang.DateUtil;
import com.yyfax.pay.order.data.service.NotifyTaskService;
import com.yyfax.pay.order.data.service.QueryTaskService;
import com.yyfax.pay.order.model.po.NotifyTaskPO;
import com.yyfax.pay.order.model.po.QueryTaskPO;
import com.yyfax.pay.quartz.jobs.NotifyPayOrderJob;
import com.yyfax.pay.quartz.jobs.QueryJobDispatcher;
import com.yyfax.pay.quartz.model.vo.DynamicJobVO;
import com.yyfax.pay.quartz.service.PayTaskService;

/**
 * 支付相关任务封装
 * 
 * @author jiangmy
 * @date 2017-04-17 11:45:56
 * @since v1.0.0
 */
@Service
public class PayTaskServiceImpl implements PayTaskService {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private QueryTaskService queryTaskService;
	@Autowired
	private NotifyTaskService notifyTaskService;

	private DynamicJobVO createQueryJob(QueryTaskPO task) {
		if (StringUtils.isBlank(task.getNextTime())) {
			task.setNextTime(task.getStartTime());
		}
		if (StringUtils.isBlank(task.getNextTime())) {
			task.setNextTime(DateUtil.datetime2Str(DateUtil.addSecond(new Date(), 60)));
		}
		if (task.getOptNo() == null) {
			task.setOptNo(0);
		}

		DynamicJobVO dynamicJob = new DynamicJobVO(task);
		// // 查询支付订单
		// if (QueryTaskTypeEnum.PAY.isValue(task.getType())) {
		// dynamicJob.target(QueryPayOrderJob.class);
		// }
		// // 查询代付订单
		// else if (QueryTaskTypeEnum.PAYOUT.isValue(task.getType())) {
		// dynamicJob.target(QueryPayoutOrderJob.class);
		// }
		// // 查询批量代付订单
		// else if (QueryTaskTypeEnum.PAYOUT_BATCH.isValue(task.getType())) {
		// dynamicJob.target(QueryBatchPayoutOrderJob.class);
		// }
		// // 查询批量代付对账订单
		// else if (QueryTaskTypeEnum.PAYOUT_BATCH_RECONCILIATION.isValue(task.getType())) {
		// dynamicJob.target(QueryBatchPayoutOrderCheckJob.class);
		// }
		// // 查询代扣订单
		// else if (QueryTaskTypeEnum.PAYIN.isValue(task.getType())) {
		// dynamicJob.target(QueryPayinOrderJob.class);
		// }
		// // 查询批量代扣订单
		// else if (QueryTaskTypeEnum.PAYIN_BATCH.isValue(task.getType())) {
		// dynamicJob.target(QueryBatchPayinOrderJob.class);
		// }
		// 调度触发器
		dynamicJob.target(QueryJobDispatcher.class);

		dynamicJob.addOrderData(task);
		dynamicJob.cronExpression(DateUtil.date2Str(DateUtil.str2DateTime(task.getNextTime()), "s m H d M ? yyyy")); // "0 15 10 * * ? 2015"
																														// 2015年的每天早上10：15触发
		try {
			com.yyfax.pay.quartz.dynamic.DynamicSchedulerFactory.registerJob(dynamicJob);
		} catch (SchedulerException e) {
			throw new IllegalStateException(e);
		} finally {
			logger.info("【添加任务】{}", task);
			logger.info("【添加Quartz】{}", dynamicJob);
		}

		return dynamicJob;
	}

	@Override
	public void queryTask(QueryTaskPO task) throws Exception {
		// 1.持久化
		int id = queryTaskService.save(task);
		task.setId(id);

		// 2.添加到quartz任务
		createQueryJob(task);
	}

	@Override
	public void notifyTask(NotifyTaskPO task) throws Exception {
		boolean isDuplicate = false; // 是否重复标识
		try {
			// 1.持久化
			notifyTaskService.save(task);
		} catch (DuplicateKeyException e) {
			// 更新异步通知异常，则更新异步通知任务调度信息
			logger.warn("保存异步通知任务，出现主键冲突，更新异步任务调度信息，task:{}", task);
			notifyTaskService.updateTaskByMerchantAndOrderId(task);
			isDuplicate = true;
		}

		// 2.添加到quartz任务
		createNotifyJob(task, isDuplicate);
	}

	private DynamicJobVO createNotifyJob(NotifyTaskPO task, boolean isDuplicate) {
		// 如果下次执行时间为空，且开始时间要晚于当前时间
		if (StringUtils.isBlank(task.getNextTime())) {
			if (DateUtil.str2DateTime(task.getStartTime()).after(new Date())) {
				task.setNextTime(task.getStartTime());
			}
		}

		if (StringUtils.isBlank(task.getNextTime())) {
			// 如果下次执行时间早于当前时间，则默认加500毫秒，解決quartz执行时间早于当前时间无法触发问题
			Date nextDate = new Date(System.currentTimeMillis() + 1000);
			task.setNextTime(DateUtil.datetime2Str(nextDate));
		}

		if (task.getOptNo() == null) {
			task.setOptNo(0);
		}

		String cornEx = DateUtil.date2Str(DateUtil.str2DateTime(task.getNextTime()), "s m H d M ? yyyy");

		DynamicJobVO dynamicJob = new DynamicJobVO(task);
		// dynamicJob.cronExpression(DateUtil.date2Str(DateUtil.str2DateTime(task.getNextTime()), "s m H d M ? yyyy"));
		dynamicJob.cronExpression(cornEx);
		dynamicJob.target(NotifyPayOrderJob.class);
		dynamicJob.addOrderData(task);
		// dynamicJob.addJobData("mailGuid", UUID.randomUUID().toString());// transfer parameter

		try {
			if (isDuplicate) {
				// 如果重复下单，则更新调度机制
				com.yyfax.pay.quartz.dynamic.DynamicSchedulerFactory.updateJob(dynamicJob);
			} else {
				com.yyfax.pay.quartz.dynamic.DynamicSchedulerFactory.registerJob(dynamicJob);
			}
		} catch (SchedulerException e) {
			throw new IllegalStateException(e);
		} finally {
			logger.info("【添加异步通知任务】{}", task);
			logger.info("【添加异步通知任务Quartz】{}", dynamicJob);
		}
		return dynamicJob;
	}
}
